package org.bambrikii.dictionary.dao;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.bambrikii.dictionary.Article;
import org.bambrikii.dictionary.Word;
import org.bambrikii.dictionary.WordContext;
import org.bambrikii.site.base.core.dao.DAOBase;
import org.bambrikii.site.base.persistence.PersistenceConnector;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

public class WordContextDAO extends DAOBase<WordContext> implements IWordContextDAO {
	public WordContextDAO(final PersistenceConnector connector) {
		super(connector);
	}

	public WordContext find(final Article article, final Word word) {
		final Criteria crit = getCriteria();
		crit.add(Restrictions.eq("article", article));
		crit.add(Restrictions.eq("word", word));
		return (WordContext) crit.uniqueResult();
	}

	public Map<String, Map<Integer, String>> getContexts(final Article article,
			final List<String> words) {
		final Query q = getConnector()
				.getSession()
				.createQuery(
						"select w1.value, ctx1.article.id, ctx1.meaning from WordContext ctx1 join ctx1.word w1 where ctx1.article = :a2 or w1.value in ( :w2 ) ");
		q.setParameter("a2", article).setParameterList("w2", words);
		@SuppressWarnings("unchecked")
		final List<Object[]> list1 = q.list();

		final Map<String, Map<Integer, String>> result = new LinkedHashMap<String, Map<Integer, String>>();
		for (final Object[] objs : list1) {
			final String w = (String) objs[0];
			final Integer a = (Integer) objs[1];
			final String ctx = (String) objs[2];
			Map<Integer, String> w2 = result.get(w);
			if (w2 == null) {
				w2 = new LinkedHashMap<Integer, String>();
				result.put(w, w2);
			}

			w2.put(a, ctx);
		}
		return result;
	}
}
